import {
  api,
  util,
  dialog,
  clickIncrement,
  clearIncrement,
  storage
} from '../../../../js/util';
import {
  router
} from '../../../../js/router';
import {
  order,
  fee,
  grouporder,
  retreat
} from '../../../../js/modules/order';
import {
  address,qywx
} from '../../../../js/modules/store';
import {
  annex
} from '../../../../js/modules/annex';
import authorize from '../../../../js/modules/authorize';
import {
  config,
  area
} from "../../../../js/modules/gloab";
import {
  upload
} from '../../../../js/modules/material.js'
var app = getApp();
import BasePage from '../../../../js/common/base-page'
import { getFuzzyLocation } from '../../../../js/authSetting';
import { alert, deepClone, isEmpty, type } from '../../../../js/newUtil';
BasePage({
  pageKey:"orderConfirm",
  /**
   * 页面的初始数据
   */
  data: {
    imgDomain: api.imgDomain,
    enableOss: api.enableOss,
    modalType: "invo",
    spOder: [], //供应商的各订单数据  
    payData: [],
    defaultAdr: [], //显示的地址
    consignee: {
      AddressId: 0,
      Province: '',
      City: '',
      Area: '',
      Address: '',
      Name: '',
      Mobile: ''
    },
    CouponIds: 0,
    CouponsCount: 0, //优惠劵可使用数量
    couponsText: "无可用优惠券",
    couponsList: [], //优惠劵
    couponAllowSuperpose: false, //支持多张优惠券
    invoice: "<Invoice><InvType>0</InvType></Invoice>",
    invoiceInfo: {
    },
    NowInvoiceRate: 0, //当前发票税率
    invoiceRate: {
      ZZInvoiceRate: 0, //获取增值税发票税率
      PTInvoiceRate: 0, //获取普通发票税率 
      IsInvoice: false,
      FreightMode: 1, //订单运费计算模式：1标准模式  2商品指定运费模式   
    },
    InvoiceId: 0, //发票类型
    InvoiceType: 0,
    Weight: 0, //重量
    Freight: 0.00, //运费
    Taxes: 0.00, //税费
    ProductAmount: 0.00, //货品总金额
    TotalIntegral: 0, //使用积分
    CouponDiscount: 0.00, //优惠劵优惠金额
    PayDiscount: 0.00, //支付优惠金额
    DiscountAmount: 0.00, //购物车优惠金额
    Payables: 0.00, //实际付款金额
    PayableIntegral: 0, //实付积分
    PayTypeId: 1, //支付方式 
    DeductionIntegral: 0, //抵扣的积分
    AccountIntegral: 0, //账户积分
    MaxUseIntegral: 0, //账户可用积分
    UseIntegral: 0, //能够使用的积分
    DeductionTotal: 0.00, //积分抵扣的金额
    BuyRemark: '', //订单备注
    RemarkTips: '',
    deductRate:0,//抵扣比例
    useGrade: true,
    isInitOrder: false,//是否初始化订单
    isSubmitOrder: false,//是否正在提交
    showModalStatus: false,
    //固定变量
    fixedVariable: {
      Quantity: '',
      ProductIds: '',
      ProductInfo: '',
      IsDelivery: false
    },
    uploadImageList:[],
    virtualImageList:[],
    quantityDigits: 0,
    priceDigits: 2,//价格显示小数位数
    openDeliveryTime:false,    //开启送货时间设置
    deliveryTime:'',      //送货时间
    deliveryBeginTime:'',  //送货开始时间
    deliveryEndTime:'', //送货结束时间
    expressList:[],  //快递公司
    express:0,    //默认选中快递公司索引
    showlink:false,   //是否显示qywx联系人按钮
    IsNecessityAddress:true, // 是否选择地址
    IsAddressToReal: false, // 收货地址验证增强，开启后需要验证地址完整性（省市区和地址详情都需要填写）
    IsEnableSelfPickup:true,//是否开启买家自提
    PickpointAddress: false, // 自提时，是否需要填写收货地址
    IsEnableLogisticsExp:true,//是否开启物流快递
    IsStoreDelivery: true, // 是否开启商家配送
    navActive: 2,
    SelfAdr:{},//自提地址
    lat:'',//维度
    lng:'',//经度
    addrNum:'',//自提id
    categories:0,//商品种类
    isIphoneX:app.globalData.isIphoneX,
    mainColor:'',//主题色
    Currency:'',//货币符号
    customFileds:[],//自定义订单
    customInfosList: [], //已填写的自定义订单
    couponTabList: ['可用优惠券','不可用优惠券'],
    couponTab:0,//可用和不可用
    couponsNum:0,
    showReceiveType: false, // 显示切换按钮
    logisticsModeDisplayName: ['物流快递', '到店自提', '商家配送'], // 物流方式名称设置
    defaultLogisticsMode: -1, // 默认的物流方式
    integralReduceFreight: { // 积分抵扣运费参数
      AccountIntegral: 0, // 用户可用积分
      Deduction: 0, // 最大抵扣金额
      DeductionIntegral: 0, // 此次最大可用积分
      Rate: 0, // 兑换比例
      usingIntegral: 0, // 用户要使用的积分
      originFreight: 0, // 未抵扣时的运费
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.hideShareMenu();//隐藏分享
    this.invoiceAddCom = this.selectComponent("#invoiceAddCom");
    this.deliveryComponent = this.selectComponent("#deliveryComponent");
    this.getData(options)
    let year=new Date().getFullYear()
    let month=new Date().getMonth()+1  //这里month需要+1
    let day=new Date().getDate()
    this.setData({
      time:year+'-'+month+'-'+day
    })
  },
  /**
   * 获取数据
   * 将获取下单数据和配置改为promise方法并同时调用
   * @param {*} options 页面options
   */
  getData (options) {
    let that = this
    Promise.all([this.initOrderData(options.productinfo), this.getWholesaleConfig()]).then((res) => {
      // 根据后台的默认收货方式,修改默认选中的方式
      let {
        navActive,
        defaultLogisticsMode
      } = that.data
      defaultLogisticsMode = parseInt(defaultLogisticsMode)
      if (defaultLogisticsMode != -1) {
        switch (defaultLogisticsMode) {
          case 0:
            navActive = 1 // 物流快递
            break;
          case 1:
            // 切换到自提后,需要调用获取自提点接口
            // 如果当前已经是自提则不重复调用接口
            if (navActive != 0) {
              that.bindNav({
                currentTarget: {
                  dataset: {
                    id: 0
                  }
                }
              })
            }
            navActive = 0 // 到店自提
            break;
          case 2:
            navActive = 2 // 商家配送
            break;
        }
        that.setData({
          navActive
        })
      }
    }).catch((err) => {
      console.log(err)
    })
    this.getExpress();
    this.isShowLink();
  },
  //切换--自提和快递
  bindNav:function(e,callback){
    var that = this;
    var id = e.currentTarget.dataset.id;
    if(id == 0){
      // 已存在经纬度，不再重复获取
      if (!isEmpty(that.data.lat)) {
        if(that.data.SelfAdr.Id){
          this.setData({
            navActive:id
          })
          this.checkCouponApplicability()
          return
        } else {
          that.getDataList()
          this.checkCouponApplicability()
          return
        }
      }
      getFuzzyLocation({
        type: 'gcj02', //返回可以用于wx.openLocation的经纬度
        success: function (res) {
          if (!res) return;
          console.log(res,'====getFuzzyLocation====');
          that.setData({
            lat:res.latitude,//维度
            lng:res.longitude,//经度
          })
          if(!that.data.SelfAdr.Id){
            that.getDataList();
          }
        },
        fail () {
          console.log('get location fail')
          that.setData({
            lat: 0,
            lng: 0
          })
          if(!that.data.SelfAdr.Id){
            that.getDataList()
          }
        }
      })
    }else{
      that.data.addrNum=0;
    }
    this.setData({
      navActive:id
    })
    this.checkCouponApplicability()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    //切换收货地址后，重新计算运费
    if (this.data.consignee.AddressId > 0 && this.data.consignee.PreAddressId != this.data.consignee.AddressId) {
      let { consignee}=this.data;
      consignee.PreAddressId = consignee.AddressId;
      this.deliveryComponent.parseAddress(consignee);
      this.setData({
        areaCode: consignee.code,
        consignee: consignee
      })
      this.calFreight(consignee.AddressId);
    }
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1];
    if(currPage.data.SelfAdr){
      this.setData({
        SelfAdr: this.data.SelfAdr,
        addrNum:this.data.SelfAdr.Id,
      });
    }
    this.setData({
      mainColor:api.titleColor||"#e56b14",
      Currency:api.Currency || '￥'
    })
  },
  isShowLink:function(){
    let that = this;
    qywx.showlink('orderconfir',function(res){
      that.setData({
        showlink:res=='true'
      })
    })
  },
  /*
   *加载配置项参数
   */
  getWholesaleConfig() {
    var that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    return new Promise((resolve) => {
      config.getWholesaleConfigs(
        fkid,
        fkflag,
        "Wholesale",
        (model) => {
          let showReceiveType = false
          let navActive = 2
          let IsEnableLogisticsExp = model.IsEnableLogisticsExp
          let IsEnableSelfPickup = model.IsEnableSelfPickup
          let IsStoreDelivery = model.IsStoreDelivery
          let logisticsModeDisplayName = model.LogisticsModeDisplayName || ''
          logisticsModeDisplayName = logisticsModeDisplayName.split(',')
          if (IsEnableLogisticsExp) {
            navActive = 1
          } else if (IsEnableSelfPickup) {
            navActive = 0
            that.bindNav({
              currentTarget: {
                dataset: {
                  id: 0
                }
              }
            })
          } else if (IsStoreDelivery) {
            navActive = 2
          }
          if ((IsEnableLogisticsExp && IsEnableSelfPickup) || (IsEnableLogisticsExp && IsStoreDelivery) || IsStoreDelivery && IsEnableSelfPickup) {
            showReceiveType = true
          }
          that.setData({
            priceDigits: model.PriceDigits,
            quantityDigits: model.QuantityDigits,
            addressAssignDepot: model.AddressAssignDepot,
            openDeliveryTime: model.IsOpenDeliveryTime,
            IsNecessityAddress: model.IsNecessityAddress,
            IsAddressToReal: model.IsAddressToReal,
            IsEnableSelfPickup: IsEnableSelfPickup,
            PickpointAddress: model.PickpointAddress,
            IsEnableLogisticsExp: IsEnableLogisticsExp,
            IsStoreDelivery: IsStoreDelivery,
            showReceiveType,
            navActive,
            logisticsModeDisplayName
          });
          this.deliveryComponent.getDefaultAddress();
          if (model.IsOpenDeliveryTime) {
            this.setDeliveryTime(model.DeliveryDeadLine);
          }
          console.log(model.IsNecessityAddress, '----地址', model.IsEnableLogisticsExp, model.IsAddressToReal)
          resolve()
      })
    })
  },
  /**
   * 设置送货起始时间
   */
  setDeliveryTime:function(deadLine){
    let current = new Date();
    let miniDate = util.formatGetTime(0,'-'); 
    let hour = current.getHours(), minu = current.getMinutes();
    if(deadLine!=''){
      let deadTime = deadLine.split(':');
      if((hour > Number(deadTime[0])) || ((hour == Number(deadTime[0])) && (minu > Number(deadTime[1])))){
        miniDate = util.formatGetTime(1,'-');
        hour = 0; minu = 0;
      }
    }
    let maxDate = util.getDateSt(miniDate, -364, 'date');
    let miniDateTime = miniDate+" "+[hour, minu].map(util.formatNumber).join(':');
    let maxDateTime = maxDate+" 23:59";
    this.setData({
      deliveryBeginTime:miniDateTime,
      deliveryEndTime:maxDateTime
    })
  },
  /**
   * 改变送货时间
   */
  bindDeliveryChange:function(e){
    this.setData({
      deliveryTime: e.detail
    })
  },
  /**
   * 获取快递公司
   */
  getExpress:function(){
    let that = this;
    retreat.getLogisticsList(function (data) {
      // data.unshift({Id:0,Name:'请选择快递公司'});
      // if(data.length == 0){
      //   data.unshift({Id:0,Name:'可选择快递公司'});
      // }
      that.setData({
        expressList: data
      });
    });
    this.calFreight(this.data.consignee.AddressId);
  },
  /**
   * 改变快递公司
   */
  bindExpressChange:function(e){
    this.setData({
      express:e.detail.value
    })
    //计算运费
    // console.log(this.data.consignee.AddressId,'===========运费');
    this.calFreight(this.data.consignee.AddressId);
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  /**加载订单初始化信息 */
  initOrderData(productInfo) {
    var that = this;
    wx.showLoading({
      title: '加载中'
    });
    that.setData({
      isInitOrder: true
    });
    return new Promise((resolve) => {
      order.initOrderConfirmData(productInfo, function (status, res) {
        wx.hideLoading();
        if (!status) {
          that.setData({
            isInitOrder: false
          });
          util.confirm(function () {
            router.navigateBack();
          }, function () {}, "结算失败：" + res, "温馨提示");
          resolve()
          return;
        }
        var fixedVariable = {
          Quantity: res.Quantity,
          ProductIds: res.ProductIds,
          ProductInfo: res.ProductInfo,
          IsDelivery: res.IsDelivery
        };
        var deductionIntegral = parseInt(res.DeductionIntegral) == undefined ? 0 : parseInt(res.DeductionIntegral);
        var accountIntegral = parseInt(res.AccountIntegral) == undefined ? 0 : parseInt(res.AccountIntegral);
        let deductRate = deductionIntegral > 0 ? ((res.DeductionTotal || 0) / deductionIntegral) : 0;
        var orderInfo = res;
        var category_num = 0;
        orderInfo.Suppliers.forEach((supplier) => {
          supplier.Products.forEach(product => {
            category_num += (product.Goods || []).length;
            let is_packed = false;
            product.Goods.forEach(goods => {
              if (goods.DiscountType == 5) {
                is_packed = true;
              }
            })
            if (!is_packed) {
              category_num += (product.ProGifts || []).length;
            }
          })
        })
        var coupons = res.Coupons || [];
        var amount = 0;
        var couponId = res.CouponIds || '';
        var couponIds = couponId.split(',');
        var selectGoodsIdArrays = [];
        if (res.CouponsCount) {
          coupons.map((item, index) => {
            var goodsIds = item.GoodsIds || '';
            var goodsIdArray = goodsIds != '' ? goodsIds.split(',') : [];
            if (couponIds.indexOf(String(item.CouponsId)) > -1) {
              selectGoodsIdArrays.push.apply(selectGoodsIdArrays, goodsIdArray);
            }
          });
          coupons.map((item, index) => {
            var goodsIds = item.GoodsIds || '';
            var goodsIdArray = goodsIds != '' ? goodsIds.split(',') : [];
            var isChecked = couponIds.indexOf(String(item.CouponsId)) > -1;
            var isEnable = true;
            if (!isChecked && res.CouponAllowSuperpose == true && selectGoodsIdArrays.length > 0) {
              let intersectArray = goodsIdArray.filter(li => selectGoodsIdArrays.indexOf(li) > -1);
              isEnable = !(intersectArray && intersectArray.length > 0);
            }
            item.IsChecked = isChecked;
            item.IsEnable = isEnable;
            if (isChecked && item.DiscountAmount > 0) {
              amount += item.DiscountAmount;
            }
          });
        }
        amount = util.formatFloat(amount, 2);
        let productAmount = res.TotalAmount - res.DiscountAmount - (that.data.useGrade ? 0 : res.DeductionTotal);
        if (productAmount < amount) {
          util.tips("优惠金额大于了订单金额(不含运费)");
        }
        let payTypeId = res.PayTypeId > 0 ? res.PayTypeId : (res.PayTypes && res.PayTypes.length > 0 ? res.PayTypes[0].Id : 0);
        that.setData({
          isInitOrder: false,
          PayTypeId: payTypeId,
          payData: res.PayTypes,
          spOder: res.Suppliers,
          couponsList: coupons,
          couponAllowSuperpose: res.CouponAllowSuperpose == true,
          CouponDiscount: productAmount >= amount && amount > 0 ? amount : 0.00, //优惠券金额
          CouponIds: productAmount >= amount && amount > 0 ? couponId : 0, //优惠券id
          couponsText: productAmount >= amount && amount > 0 ? ("-" + that.data.Currency + amount) : res.CouponsCount == 0 ? "选择优惠券" : '无可用优惠券',
          CouponsCount: res.CouponsCount,
          ProductAmount: res.TotalAmount,
          TotalIntegral: res.TotalIntegral,
          Weight: res.Weight,
          Payables: res.Payables,
          PayableIntegral: res.PayableIntegral,
          Freight: res.Freight,
          DeductionIntegral: res.DeductionIntegral,
          AccountIntegral: accountIntegral,
          MaxUseIntegral: accountIntegral > deductionIntegral ? deductionIntegral : accountIntegral,
          UseIntegral: accountIntegral > deductionIntegral ? deductionIntegral : accountIntegral,
          deductRate: deductRate,
          DeductionTotal: res.DeductionTotal,
          DiscountAmount: res.DiscountAmount,
          fixedVariable: fixedVariable,
          categories: category_num, //商品种类
          couponsNum: that.data.couponsNum,
          defaultLogisticsMode: res.LogisticsMode
        });
        //加载发票信息
        that.initInvoiceInfo();
        //加载订单自定义字段信息
        that.customizefields();
        // 判断优惠券可用状态
        that.checkCouponApplicability()
        resolve()
      });
    })
  },
  /**初始化订单自定义字段信息**/
  customizefields(){
    order.orderCustomization((res)=>{
      if(res){
        // 处理下拉、单选、多选显示的数据
        res.map((item)=>{
          if(item.FieldType === 'checkbox' || item.FieldType === 'select' || item.FieldType === 'radio' ) {
            let itemsValue = Object.keys(item.Items)
            let ItemList = []
            let flag = false
            if(item.FieldType === 'radio') {
              flag = true
            }
            itemsValue.map((vItem, index)=>{
              let checkedStatus = false
              if(flag && index === 0) {
                checkedStatus = true
              }
              ItemList.push({ key: vItem, value: item.Items[vItem], checked: checkedStatus })
            })
            item.ItemList = ItemList
            // itemsValue.map((vItem)=>{
            //   ItemList.push({ key: vItem, value: item.Items[vItem], checked: false })
            // })
            // item.ItemList = ItemList
          }
        })
        // console.log(res,'=======ItemList');
        res.sort((a, b) => {
          return a.Sort - b.Sort
        })
        this.setData({
          customFileds: res
        })
      }
    })
  },
  /**选择省市区**/
  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },
  /**单选**/
  radioChange(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)

    const items = this.data.items
    for (let i = 0, len = items.length; i < len; ++i) {
      items[i].checked = items[i].value === e.detail.value
    }

    this.setData({
      items
    })
  },
  /**多选**/
  checkboxChange(e) {
  },
  /**日期**/
  bindTimeChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      time: e.detail.value
    })
  },
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let index = e.currentTarget.dataset.index
    let pickerIndex = this.data.pickerIndex
    pickerIndex[index] = e.detail.value ? Number(e.detail.value) : ''
    this.setData({
      pickerIndex: pickerIndex
    })
  },
  /**初始化发票信息 */
  initInvoiceInfo() {
    var that = this;
    fee.initInvoiceInfo((res)=> {
      if (res) {
        var nowInvoiceRate = 0;
        if (res.InvoiceType == 1) {
          nowInvoiceRate = res.invoiceRate.PTInvoiceRate;
        } else if (res.InvoiceType == 2) {
          nowInvoiceRate = res.invoiceRate.ZZInvoiceRate;
        }
        that.setData({
          InvoiceId: res.InvoiceId,
          InvoiceType: res.InvoiceType,
          invoiceInfo: res.invoiceInfo,
          invoice: res.invoice,
          invoiceRate: res.invoiceRate,
          NowInvoiceRate: nowInvoiceRate
        });
        this.invoiceAddCom.initInvoice(res.invoiceInfo, res.InvoiceType);
      }
      that.calInvRate();
      that.initFreightMode(that);
    });
  },
  /**
   * 初始化运费模式
   */
  initFreightMode(that){
    /**
     * 商家免运费
     * 不免：标准模式，商品 FeeMode=2
     *      标准模式：按重量（切换地区时运费变化）FeeMode=1，按订单 FeeMode=2
     * 注：只有按重量计算的，才需要实时请求计算 
     */
    annex.isFreeFreight(function (res) {
      if (res.Success&&res.Content>0) {
        that.data.invoiceRate.FreightMode = 2;
      }
      else {
        annex.getfeemode(function (res) {
          if (res.Success) {
            var data = res.Content;

            var freightmode = data.FeeMode;

            if (freightmode == 2) {
              that.data.invoiceRate.FreightMode = 2;
              that.setData({
                invoiceRate: that.data.invoiceRate
              });

            }
          }
          if (that.data.InvoiceType == 1) {
            that.data.NowInvoiceRate = that.data.invoiceRate.PTInvoiceRate;
            that.calInvRate();
          } else if (that.data.InvoiceType == 2) {
            that.data.NowInvoiceRate = that.data.invoiceRate.ZZInvoiceRate;
            that.calInvRate();
          }
          //计算运费
          that.calFreight(that.data.consignee.AddressId);
        });
      }
    });
  },
  /**
   * 选择支付方式
   */
  chosePayWay: function(event) {
    this.setData({
      PayTypeId: event.currentTarget.dataset.val
    });
    this.checkCouponApplicability()
  },
  /**选择优惠劵 */
  selectCoupon(e) {
    var enable = e.currentTarget.dataset.enable;
    var show = e.currentTarget.dataset.show;
    var amount = parseFloat(e.currentTarget.dataset.amount);
    var couponid = e.currentTarget.dataset.couponid;
    if(!enable || show == 0 || amount <= 0) return;
    var couponsList = this.data.couponsList;
    var couponAllowSuperpose = this.data.couponAllowSuperpose;
    var selectGoodsIdArrays = [];
    couponsList.map((item, index) => {
        var goodsIdArray = [];
        if (!isEmpty(item.GoodsIds) && type.isString(item.GoodsIds)) {
          goodsIdArray = item.GoodsIds.split(',')
        }
        if (item.CouponsId == couponid) {
          item.IsChecked = !item.IsChecked;
        }else if(couponAllowSuperpose == false){
          item.IsChecked = false;
        }
        if (item.IsChecked&&goodsIdArray.length>0) {
          selectGoodsIdArrays.push.apply(selectGoodsIdArrays, goodsIdArray);
        }
    });
    couponsList.map((item, index) => {
        var goodsIdArray = [];
        if (!isEmpty(item.GoodsIds) && type.isString(item.GoodsIds)) {
          goodsIdArray = item.GoodsIds.split(',')
        }
        item.IsEnable = true;
        if (!item.IsChecked && couponAllowSuperpose && selectGoodsIdArrays.length > 0) {
          let intersectArray = goodsIdArray.filter(li => selectGoodsIdArrays.indexOf(li) > -1);
          item.IsEnable = !(intersectArray && intersectArray.length > 0);
        }
    });
    this.setData({ couponsList: couponsList });
  },
  /**确认优惠劵 */
  onComfirmCoupon(e) {
    let { ProductAmount, DiscountAmount, couponsList, DeductionTotal, useGrade } = this.data;
    let productAmount = ProductAmount - DiscountAmount - (useGrade ? 0 : DeductionTotal);
    var amount = 0, couponIds = [];
    couponsList.map((item, index) => {
      if (item.IsChecked) {
        amount += item.DiscountAmount;
        couponIds.push(item.CouponsId);
      }
    });
    amount = util.formatFloat(amount, 2);
    if (productAmount < amount) {
      util.tips("优惠金额大于了订单金额(不含运费)");
      return;
    }
    this.setData({
      CouponIds: couponIds.join(','),
      CouponDiscount: amount,
      couponsText: amount > 0 ? ("-" + this.data.Currency + amount) : this.data.CouponsCount ? "选择优惠券" : "无可用优惠券",
      showModalStatus: false
    });
    //重新计算运费
    this.calFreight(this.data.consignee.AddressId);
    //重新计算税费
    this.calInvRate();
    this.hideModal();
  },
  /**
   * 判断优惠券是否可用
   */
  checkCouponApplicability() {
    let couponsList = this.data.couponsList || []
    let {
      PayTypeId,
      navActive,
      couponAllowSuperpose
    } = this.data
    if (navActive == 1) {
      navActive = 0
    } else if (navActive == 0) {
      navActive = 1
    }
    let selectGoodsIdArrays = []
    couponsList = couponsList.map((item) => {
      item.unableWithApplicability = false // 根据条件将优惠券设为不可用，支付条件或送货方式等条件
      let goodsIdArray = []
      if (!isEmpty(item.GoodsIds)) {
        goodsIdArray = item.GoodsIds.split(',')
      }
      PayTypeId = PayTypeId.toString()
      navActive = navActive.toString()
      // 收货方式是否满足条件
      if (item.LogisticsTypeId) {
        let arr = item.LogisticsTypeId.split(',')
        if (!arr.includes(navActive)) {
          if (item.IsChecked) {
            item.IsChecked = false
          }
          item.unableWithApplicability = true
        }
      }
      // 支付方式是否满足条件
      if (item.PayTypeId) {
        let arr = item.PayTypeId.split(',')
        if (!arr.includes(PayTypeId)) {
          if (item.IsChecked) {
            item.IsChecked = false
          }
          item.unableWithApplicability = true
        }
      }
      if (item.IsChecked && goodsIdArray.length > 0) {
        selectGoodsIdArrays = [...selectGoodsIdArrays, ...goodsIdArray]
      }
      return item
    })
    // 设置优惠券显示isEnable
    couponsList = couponsList.map((item => {
      let goodsIdArray = []
      if (!isEmpty(item.GoodsIds)) {
        goodsIdArray = item.GoodsIds.split(',')
      }
      item.IsEnable = true
      if (!item.IsChecked && couponAllowSuperpose && selectGoodsIdArrays.length > 0) {
        let intersectArray = goodsIdArray.filter(li => selectGoodsIdArrays.indexOf(li) > -1)
        item.IsEnable = !(intersectArray && intersectArray.length > 0)
      }
      return item
    }))
    this.setData({
      couponsList
    })
    this.onComfirmCoupon()
  },
  /**
   * 积分抵扣
   */
  switchGrade: function(e) {
    var usegrade = !e.detail.value; //隐藏使用积分
    var that = this;
    this.data.useGrade = usegrade
    this.setData({
      useGrade: this.data.useGrade
    });
    var inputIntegral = parseInt(this.data.MaxUseIntegral);
    if (usegrade || inputIntegral == undefined || inputIntegral <= 0 || isNaN(inputIntegral)) {
      that.setData({
        UseIntegral:0,
        DeductionTotal: 0
      });
      //重新计算运费、税费
      that.calFreight(that.data.consignee.AddressId);
      that.calInvRate();
      return;
    }
    this.calIntegralDeuct(inputIntegral);

  },
  /**积分改变事件 */
  onChangeValueEvent(e) {
    var that = this;
    if (e.detail.value == "") {
      that.setData({
        DeductionTotal: 0,
        UseIntegral: ""
      });
    }
    var inputIntegral = parseInt(e.detail.value);
    if (inputIntegral == undefined || inputIntegral <= 0) {
      util.tips("请输入正整数！");
      that.setData({
        DeductionTotal: 0,
        UseIntegral: ""
      });
      return;
    }
    var param = this.getMaxIntegral(inputIntegral);
    inputIntegral = param.inputIntegral;
    that.setData({
      UseIntegral: inputIntegral
    });
  },
  /**积分离开事件 */
  onIngegralBlur(e) {
    var that = this;
    this.calIntegralDeuct(that.data.UseIntegral);
  },
  getMaxIntegral(inputIntegral){
    let { ProductAmount, DiscountAmount, CouponDiscount, deductRate } = this.data;
    let productAmount = ProductAmount - DiscountAmount - CouponDiscount;
    //最大可使用积分
    var maxUseIntegral = parseInt(this.data.MaxUseIntegral);
    productAmount / deductRate
    if (inputIntegral > maxUseIntegral) { inputIntegral = maxUseIntegral; }
    if (inputIntegral > parseInt(productAmount / deductRate)) {
      inputIntegral = parseInt(productAmount / deductRate);
    }
    return {
      inputIntegral: inputIntegral,
      payables: productAmount
    };
  },
  /**计算积分抵扣 */
  calIntegralDeuct(inputIntegral) {
    let that = this;
    var param = this.getMaxIntegral(inputIntegral);
    inputIntegral = param.inputIntegral;
    if (that.data.navActive == 1) {
      param.Amount = that.data.Payables
    } else {
      param.Amount = that.data.Payables - that.data.Freight
    }
    that.setData({
      UseIntegral: inputIntegral
    });
    fee.calDeductionTotal(param, function (deductionTotal) {
      that.setData({
        DeductionTotal: parseFloat(deductionTotal)
      });
      //重新计算运费、税费
      that.calFreight(that.data.consignee.AddressId);
      that.calInvRate();
    });
  },
  // 检查自定义订单信息是否填写完整
  checkCustomInfo() {
    let flag = true
    let customInfosList = this.data.customInfosList // 已填写的信息
    let customFileds = this.data.customFileds // 原始数据
    let toastText = ''
    // 未填写任何信息
    if(customInfosList.length <= 0) {
      for(let i = 0; i < customFileds.length; i++) {
        if(customFileds[i].IsRequired === 1) {
          flag = false
          toastText = `${customFileds[i].FieldName}未填写`
          break
        }
      }
    } else{
      for(let i = 0; i < customFileds.length; i++) {
        if(customFileds[i].IsRequired === 1) {
          let mFlag = true
          for(let j = 0; j < customInfosList.length; j++) {
            if(customFileds[i].Id === customInfosList[j].dataId) {
              mFlag = false
              if(customInfosList[j].value.length <= 0) {
                flag = false
                toastText = `请完善${customFileds[i].FieldName}`
                break
              }
            }
          }
          if(mFlag) {
            flag = false
            toastText = `请完善${customFileds[i].FieldName}`
            break
          }
        }
      }
    }
    if(!flag) {
      util.tips(toastText);
      return false
    }
    return true
  },
  // 组装自定义订单数组
  formateOrderData() {
    let list = ''
    let customInfosList = this.data.customInfosList // 已填写的信息
    customInfosList.map((item) =>{
      let value = ''
      if(Array.isArray(item.value)) {
        value = item.value.join(',')
      } else {
        value = item.value
      }
      list += `<item_${item.dataId}>${value}</item_${item.dataId}>`
    })
    let finalXml = `<CustomizeFields>${list}</CustomizeFields>`
    return finalXml
  },
  /**
   * 提交订单
   */
  submitOrder: function() {
    var that = this;
    let navActive = this.data.navActive
    let PickpointAddress = this.data.PickpointAddress
    let integralReduceFreight = this.data.integralReduceFreight || {}
    if (that.data.isInitOrder) return;
    // 快递和商家配送需要收货地址，自提时，根据后台设置，判断是否需要收货地址
    if (navActive == 1 || navActive == 2 || PickpointAddress) {
      if (that.data.IsNecessityAddress){
        if(that.data.consignee.AddressId==0){
          util.tips("请选择收货地址");
          return;
        }
      }
      if (that.data.IsAddressToReal) { // 校验地址完整性
        let consignee = that.data.consignee || {}
        if (isEmpty(consignee.Province) || isEmpty(consignee.City) || isEmpty(consignee.Area) || isEmpty(consignee.Address)) {
          // 如果没有省市区和详细地址，则阻止提交
          alert('请完善收货地址')
          return
        }
      }
    }
    if(navActive == 1){ 
      // !that.data.expressList[that.data.express].Id
      if(that.data.expressList.length == 0 && that.data.IsEnableLogisticsExp){
        util.tips("平台尚未配置快递公司，请联系管理员进行处理");
        return;
      }else if(that.data.navActive == 0 && that.data.IsEnableLogisticsExp){
        util.tips("平台尚未配置快递公司，请联系管理员进行处理");
        return;
      }
    } else if (navActive == 0) {
      if(!that.data.addrNum){
        util.tips("请选择自提点");
        return;
      }
    }
    var payTypeId = that.data.PayTypeId;
    var isSelectPayType = false;
    that.data.payData.map(function (item) {
      if (item.Id == payTypeId) {
        isSelectPayType = true;
      }
    });
    if (!isSelectPayType) {
      util.tips("请选择支付方式");
      return;
    }

    // 检查自定义订单信息
    const customFlag = that.checkCustomInfo()
    if(!customFlag) {
      return
    }
    // 获取输入的自定义订单数据
    const orderData = that.formateOrderData();
    
    clickIncrement(function(){
      if (that.data.isSubmitOrder) return;
      that.setData({
        isSubmitOrder: true
      });
      var fixedVariable = that.data.fixedVariable;
      let DeliveryId = 0
      if (that.data.navActive == 1) {
        if (that.data.IsEnableLogisticsExp && that.data.expressList.length != 0) {
          DeliveryId = that.data.expressList[that.data.express].Id
        }
      }
      var param = {
        Quantity: fixedVariable.Quantity,
        ProductIds: fixedVariable.ProductIds,
        ProductInfo: fixedVariable.ProductInfo,
        IsDelivery: fixedVariable.IsDelivery,
        Taxes: that.data.Taxes,
        consignee: that.data.consignee,
        AddressProvince: that.data.consignee.Province,
        PayTypeId: payTypeId,
        DiscountAmount: that.data.DiscountAmount,
        Payables: that.data.Payables,
        PayableIntegral: that.data.PayableIntegral,
        InvoiceId: that.data.InvoiceId,
        InvoiceType: that.data.InvoiceType,
        UseIntegral: that.data.useGrade?0:(that.data.UseIntegral == "" ? 0 : that.data.UseIntegral),
        DeductionTotal: that.data.useGrade ? 0 :that.data.DeductionTotal,
        BuyRemark: that.data.BuyRemark,
        spOder: that.data.spOder,
        invoice: that.data.invoice,
        areaCode: that.data.areaCode,
        CouponDiscount: that.data.CouponDiscount,       
        CouponIds: that.data.CouponIds,
        VirtualImage: that.data.virtualImageList,
        DeliveryId: DeliveryId,
        DeliveryTime: that.data.deliveryTime,
        PickPointId: that.data.navActive == 0 ? that.data.addrNum : 0,
        orderData:orderData,
        IsDelivery: (navActive == 1 && that.data.IsEnableLogisticsExp) ?  1 : 0,
        LogisticsMode: navActive == 2 ? 2 : (navActive == 1 ? 0 : 1),
        FreightDeductionIntegral: 0, // 积分抵扣运费时，使用的积分数
      }
      // 自提时，并且没有开启 自提需要收货地址，那么不传地址信息
      if (navActive == 0 && !PickpointAddress) {
        param.consignee = {}
        param.consignee.AddressId = 0
        param.needNotConsignee = true
      }
      if (integralReduceFreight.originFreight > 0 && integralReduceFreight.usingIntegral > 0) {
        param.FreightDeductionIntegral = integralReduceFreight.usingIntegral
      }
      var xmlAary = order.packOrderInfo(param)
      order.submitOrder(xmlAary,function(res) {
        if (res.Success) {
          var foundOrderId=res.Content;
          wx.showLoading({
            title: '订单提交中....',
            mask: true
          });
          that.loopCount = 0;
          if (that.timer_callback){
            clearTimeout(that.timer_callback);
          }
          that.timerCallBack(that,foundOrderId,function(){
            wx.hideLoading()
          });
        }else{
          util.tips(res.Message);
          that.setData({
            isSubmitOrder: false
          });
        }

      });
    })
  },
  timer_callback:null,
  loopCount:0,
  /**定时回调 */
  timerCallBack(that,foundOrderId,callback){
    
    that.timer_callback=setTimeout(function () {
      that.loopCount++;
      order.orderCallBack(foundOrderId, function (res) {
        if(res.Success&&res.Content.length>0){
          var content=res.Content[0];
          //IsBack订单是否回写，如果是就停止轮循
          if (content.IsBack == 1 || content.IsBack==true){ 
            callback();       
            clearTimeout(that.timer_callback); 
            that.parseContent(that, { Success: true, Content: content.Content });
            
            that.loopCount = 0;
            
            return;
          }
          
        }
        if (that.loopCount > 9) {
          callback();
          clearTimeout(that.timer_callback);
          that.parseContent(that, { Success: false, Message: "请求超时..", Code:api.timeoutCode});
          
          that.loopCount = 0;
          
        }
        else{
        that.timerCallBack(that, foundOrderId,callback);
        }
      });
    },1000);
  
  },
  /**解析回调的内容 */
  parseContent(that,res){
    if (res.Success) {
      var content = res.Content;

      if (content.Result == 1) {
        var payables = that.data.Payables;
        payables = payables == undefined ? 0 : payables
        var payTypeId=that.data.PayTypeId;
        //1.货到付款、5.线下付款，跳转到支付成功页面  
        router.redirect({
          path: "cashier",
          params: {
            recordData: content.Data,
            payStatus: (payTypeId == 1 || payTypeId == 5 || payables == 0) ? 1 : 0,
            pagetype: 'order'
          }
        });
        that.setData({
          isSubmitOrder: false
        });

      } else {
        //显示错误信息
        var msg = "订单提交失败！"+content ;
        if (typeof content === "string" && content.indexOf("ERROR") > -1) {
          var resp = content.split("|:|");
          if (resp.length < 2) {
            msg = ("订单提交失败！");
          } else {
            msg = (resp[1]); //显示错误信息
          }
        }
        util.alert(msg);
        that.setData({
          isSubmitOrder: false
        });
      }
    }
    else {
      //显示错误信息
     
      if (res.Code == api.timeoutCode) {
        router.navigate({
          path: "orderList"
        });
      }
      else{
        util.alert(res.Message);
      }
      that.setData({
        isSubmitOrder: false
      });
    }
  },
  
  /**
   * 地址选择
   */
  goAddr: function() {
    router.navigate({
      path: "addressList",
      params: {
        id: this.data.consignee.AddressId
      }
    });
  },
   /**
   * 自提选择
   */
  bindAddr:function(e){
    router.navigate({
      path: "selfList",
      params: {
        id: e.currentTarget.dataset.id,
        lng: this.data.lng,
        lat: this.data.lat
      }
    });
  },
  // 导航
  bindOpenNav:function(e){
    var item = e.currentTarget.dataset.item;
    wx.openLocation({        
      latitude: item.Latitude,  
      longitude: item.Longitude,
      name: item.Name,
      address: item.Province+item.City+item.Area+item.Address,
      scale: 28
    })
  },
  /**计算运费 */
  calFreight(addressId){
    var that = this;
    var orderInfo = that.data.spOder;
    var totalFreight = 0;
    var quantity = 0;//排除免邮数量
    var weight = 0;//排除免邮重量
    var amount = 0;//排除免邮金额
    // var SupplierId = '';
    var flag = 1;//等于1，表示全部都是促销免邮的商品，不需要计算邮费
    orderInfo.forEach(function(s){
      s.Products.forEach(function(g){
        g.Goods.forEach(function(p){
          // if(p.FreeFreight != true && p.IsGift != true){
          if(!p.FreeFreight && !p.IsGift){
            quantity += p.Quantity;
            weight += p.Weight * p.Quantity;
            amount += p.Amount;
            flag = 0;
          }
          // SupplierId = s.SupplierId;
        })
      })
    })
    // console.log(that.data.express,'======',that.data.expressList);
    setTimeout(function(){
      amount = amount-(that.data.useGrade ? 0 :that.data.DeductionTotal)-that.data.CouponDiscount
      let DeliveryId = 0
      if (that.data.navActive == 1) {
        if (that.data.IsEnableLogisticsExp && that.data.expressList.length != 0) {
          DeliveryId = that.data.expressList[that.data.express].Id
        }
      }
      var param = {
        Weight: weight,
        AddressId: addressId,
        Price: that.getPayables(true,true),
        DeliveryId: DeliveryId,
        BuyCount:quantity,
        FreightAmount:amount,
        FreightMode: 1,
        FreeFreight: false,
        // SupplierId:SupplierId,
        flag:flag
      };
      fee.calFreight(param, function(freight) {
        totalFreight += parseFloat(freight)
        if (!that.data.IsEnableLogisticsExp) {
          totalFreight = 0.00
        }
        that.setData({
          Freight: totalFreight
        })
        that.setPayables()
        fee.integralReduceFreight(totalFreight).then((res) => {
          let integralReduceFreight = res.Content || {}
          integralReduceFreight.originFreight = totalFreight
          that.setData({
            integralReduceFreight
          })
        }).catch((err) => {
          console.log(err)
        })
      })
    },300)
  },
  /**计算税费 */
  calInvRate() {
    var param = {
      ProductAmount: this.data.ProductAmount - this.data.DiscountAmount,
      NowInvoiceRate: this.data.NowInvoiceRate,
      CouponDiscount: this.data.CouponDiscount,
      DeductionTotal: this.data.useGrade ? 0 : this.data.DeductionTotal
    };
    var taxes = fee.calInvRate(param);
    this.setData({
      Taxes: taxes
    });
    this.setPayables();
  },
  /**
   * 切换发票
   */
  onSwitchInvoiceEvent(evt){
    let invoiceType =parseInt(evt.currentTarget.dataset.val);
    let  nowInvoiceRate = 0;
    switch (invoiceType) {
      case 0:
        this.data.invoice = "<Invoice><InvType>0</InvType></Invoice>";
        break;
      case 1:
        nowInvoiceRate = this.data.invoiceRate.PTInvoiceRate;
        break;
      case 2:
        nowInvoiceRate = this.data.invoiceRate.ZZInvoiceRate;
        break;
    }
    this.setData({
      InvoiceType: invoiceType,
      NowInvoiceRate: nowInvoiceRate,
      invoice: this.data.invoice
    },()=>{
      if (invoiceType==0){
        this.calInvRate();
      }else{
        this.invoiceAddCom.onSwitchInvoiceEvent(invoiceType);
      }
    });

  },
  /**发票回调 */
  onInvoiceCallbackEvent(e){
    this.setData(e.detail.content,()=>{
      this.calInvRate();
    })
  },
  /**隐藏弹出层 */
  hideModal() {
    var that = this;
    that.setData({
      showModalStatus: false
    }); //显示文本域
    dialog.hideModal(that, 'showModalStatus')
  },

  /**订单备注 */
  BuyRemarkInput(e) {
    var value = e.detail.value;
    var len = parseInt(value.length);
    if (len > this.data.max) return;
      this.setData({
        currentWordNumber: len,
        RemarkTips: e.detail.value
      });
  },
  /**
   * 确认输入
   */
  onComfirmRemark(e) {
    this.setData({
      BuyRemark: this.data.RemarkTips
    });
    this.hideModal();
  },
  /**
   * 显示留言弹层
   */
  showMsgModal(evt) {
    this.setData({
      modalType: "msg",
      RemarkTips: this.data.BuyRemark
    });
    dialog.showModal(this, 'showModalStatus')
  },
  /**显示优惠劵弹出层 */
  showCouponList(evt) {
    this.setData({
      modalType: "coupon"
    });
    dialog.showModal(this, 'showModalStatus')
  },
 
  /**计算订单价格 */
  setPayables() {
    this.setData({
      Payables: this.getPayables()
    });
  },
  /**
   * 获得支付价格
   */
  getPayables(isContain=true,isCalcFreight=false){
    var params = {
      Freight: this.data.Freight, //运费
      Taxes: this.data.Taxes, //税费
      ProductAmount: this.data.ProductAmount, //货品总金额 
      CouponDiscount: this.data.CouponDiscount, //优惠劵优惠金额
      PayDiscount: this.data.PayDiscount, //支付优惠金额
      DiscountAmount: this.data.DiscountAmount, //购物车优惠金额   
      DeductionTotal: this.data.DeductionTotal, //积分抵扣的金额
      useGrade: this.data.useGrade
    }
    return fee.calPayables(params, isContain, isCalcFreight);
  },

  onUnload: function(e) {
    this.data.pre_page = this.getPreData();
    this.data.pre_page.data.is_search = true;
    clearIncrement();
  },
  getPreData: function() {
    const pages = getCurrentPages();
    const length = pages.length;
    const prePage = pages[length - 2]; //上一页
    return prePage;
  },
  /**
   * 上传
   */
  bindUploadEvent: function (e) {
    var idx = e.currentTarget.dataset.idx;
    var that = this;
    if (this.data.uploadImageList.length >= 9) {
      util.tips("最多只能上传9张");
      return;
    }
    var count = 9 - this.data.uploadImageList.length;
    wx.chooseImage({
      count: count,
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        tempFilePaths.map(function (item) {
          that.data.uploadImageList.push(item);
        })
        that.setData({
          uploadImageList: that.data.uploadImageList
        });
        var data = {num:3001,type:3,tempFilePaths:tempFilePaths};
        upload.upload_image_server(data, function (image_list) {
          if (image_list.length==0){
            util.alert("上传失败");
            return;
          }
          image_list.map(function (item) {
            that.data.virtualImageList.push(item);
          });
        })
      }
    });
  },
  /**
 * 删除
 */
  onDelImageEvent: function (e) {
    var that = this;
    var imgidx = e.currentTarget.dataset.imgidx;
    var image_list = that.data.uploadImageList;
    image_list.splice(imgidx, 1);
    var virtual_list = that.data.virtualImageList;
    virtual_list.splice(imgidx, 1);
    that.setData({
      uploadImageList: image_list,
      virtualImageList: virtual_list
    })
  },
  chooseFileComplete (e) {
    let list = e.detail.fileList || []
    // list = list.map((item) => {
    //   return item.src || ''
    // })
    this.setData({
      virtualImageList: list
    })
  },
  /**
   * 配送至弹层选择地址
   */
  selectedAdress(e) {
    let that = this;
    this.data.areaCode = e.detail.Code;
    let d = e.detail;
    if (this.data.addressAssignDepot){
      if (this.data.areaCode!=""){
        if(d.Id&&d.Id>0){
          this.parseAddress(d);
          return;
        }
      }
      address.getAddressByName(d, (ads) => {
        if (ads && Object.keys(ads).length > 0) {
          that.deliveryComponent.parseAddress(ads);
          that.data.areaCode = ads.code;
          that.parseAddress(ads);
        }else{
          that.getDefaultAddress();
          util.confirm(function() {
            that.goAddr();
          }, function() {}, "您在浏览过程中选择了一个区域，请完善收货信息", "温馨提示")
        }
      })
    }
   else{
      this.getDefaultAddress();
   }
  },
  /**默认地址加载 */
  getDefaultAddress() {
    var that = this;
    var adrId = that.data.consignee.AddressId;
    if (adrId == 0) {
      address.getDefaultAddress(function(ads){
        if (ads!=undefined&&Object.keys(ads).length>0) {
          that.parseAddress(ads);
        }
      });
    }
  },
  parseAddress(ads){
    var consignee = {
      AddressId: ads.AddressId||ads.Id,
      PreAddressId: ads.AddressId || ads.Id,
      Province: ads.Province,
      City: ads.City,
      Area: ads.Area,
      Address: ads.Address,
      Name: ads.Name,
      Mobile: ads.Mobile
    }
    this.setData({
      defaultAdr: ads,
      consignee: consignee
    });
  },
  preventTouchMove() {

  },
  /**
   * 进入商品清单
   */
  goGoodsList:function(){
    router.navigate({
      path:'orderGoodsList',
      params:{}
    })
  },
  // 自提
  getDataList:function(){
    var that = this;
    var data = {lng:this.data.lng,lat:this.data.lat,PageIndex:1,PageSize:1};
    address.selfAddressList(data,function(content){
      if (content.Success) {
        var data = content.Content.data;
        if (data.length > 0) {
          if (data[0].distance > 1000) {
            data[0].distance = (data[0].distance / 1000) + 'km'
          } else if (data[0].distance >= 0) {
            data[0].distance = data[0].distance + 'm'
          } else {
            data[0].distance = '0m'
          }
          that.setData({
            SelfAdr: data[0],
            addrNum: data[0].Id
          })
        } else {
          util.tips("附近没有可选自提点噢！");
        }
      } else {
        util.tips("附近没有可选自提点噢！");
      }
    })
  },
  /**
   * 自定义模块
   */
   // 多选
  checkbocCallBack(e){
    this.dealCustomInfosList(e)
  },
  // 单选
  radioCallBack(e){
    this.dealCustomInfosList(e)
  },
  // 下拉列表
  selectCallBack(e){
    this.dealCustomInfosList(e)
  },
  // 输入框 文本域
  inputCallBack(e){
    this.dealCustomInfosList(e)
  },
  // 图片
  uploadImageCallBack(e){
    this.dealCustomInfosList(e)
  },
  // 地区 
  onColumnChangeEvent(e){
    this.dealCustomInfosList(e)
  },
  // 日期
  dateChangeCallBack(e){
    this.dealCustomInfosList(e)
  },
  // 处理自定义订单输入的公用方法
  dealCustomInfosList(event) {
    let value = event.detail
    console.log(value)
    if(!value) {
      wx.showToast({
        title: '数据格式错误',
        icon: 'none'
      })
      return
    }
    let customInfosList = this.data.customInfosList
    let flag = false
    if(customInfosList.length <= 0) {
      customInfosList.push(value)
      return
    }
    for(var i = 0; i < customInfosList.length; i++) {
      if(customInfosList[i].dataId === value.dataId) {
        customInfosList[i] = value
        flag = true
        break
      }
    }
    if(!flag) {
      customInfosList.push(value)
    }
    this.setData({
      customInfosList: customInfosList
    })
  },
  //优惠券Tab
  changeTabCoupon(e){
    let { couponTab } = this.data;
    if (couponTab == e.detail.currentNum.id) return;
    couponTab = parseInt(e.detail.currentNum.id);
    this.setData({ couponTab:couponTab });
  },
  //联系管家
  bindHouse(){
    router.navigate({
      path: "clerkCard"
    });
  },
  /**
   * 显示积分抵扣运费弹窗
   */
  showIntegralReductFreight () {
    let that = this
    let component = this.selectComponent('#integralReduceFreight')
    let {
      integralReduceFreight
    } = this.data
    component.$$showComponent({
      data: {
        integralReduceFreight
      },
      success (res) {
        that.setData({
          integralReduceFreight: res.integralReduceFreight,
          Freight: res.Freight || 0.00
        })
        that.setPayables()
      },
      fail (err) {
        console.log(err)
      }
    })
  }
})